import os
import sys
import argparse

from EnvironmentFile import EnvironmentFile
from Interface import Interface

EnvFile = EnvironmentFile(os.path.join(os.path.dirname(sys.executable), r"environments.json"))
# EnvFile = EnvironmentFile()


class Commands:
    @staticmethod
    def create(env_name):
        EnvFile.create_environment(env_name)

    @staticmethod
    def delete(env_name):
        print()
        print("The following environment will be DELETED:")
        print(EnvironmentFile.environment_format(EnvFile.get_environment(env_name)))
        if input("Proceed (y/[n])?") == "y":
            EnvFile.delete_environment(env_name)

    @staticmethod
    def list():
        print()
        print("Environments:")
        for name in EnvFile.get_environment_names():
            print(f"\t{name}\t{EnvFile.get_environment(name)["description"]}")

    @staticmethod
    def enter(env_name):
        Interface(EnvFile, env_name).interactive()

    @staticmethod
    def run(env_name, *command):
        Interface(EnvFile, env_name).execute(" ".join(command))

    @staticmethod
    def info(env_name):
        print()
        print(EnvironmentFile.environment_format(EnvFile.get_environment(env_name)))

    @staticmethod
    def copy(old_name, new_name):
        old_env = EnvFile.get_environment(old_name)
        EnvFile.create_environment(new_name)

        EnvFile.set_description(new_name, f"Copied: {old_env["description"]}")
        for key, value in old_env["variables"].items():
            for v in value:
                EnvFile.append_variable(new_name, key, v)
                EnvFile.save()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    group = parser.add_argument_group("commands")
    group.add_argument(
        "COMMAND",
        choices=["create", "delete", "list", "enter", "run", "info", "copy"]
    )
    group.add_argument("other_args", nargs=argparse.REMAINDER)
    cmd_args = parser.parse_args()

    Commands.__dict__[cmd_args.COMMAND](*cmd_args.other_args)
